import Storage from "../utils/Storage.class";
import ServiceConfig from "../config/ServiceConfig.class";
import PType from "../utils/PType.class";
import Utils from "../utils/Utils.class";
// import Modal from "../utils/Modal.class";

const TAG = "[Service.class.js]";

///服务器相关的配置
let serviceOptions = {};

///重置服务参数
function resetServiceOptions(options) {
    ///深度同步参数
    serviceOptions = Utils.mergeClass({}, ServiceConfig, options);
}

///通用基础service
export default class Service {
    constructor(serviceConf) {

        ///判断如果不为空的话，需要传递一个ServiceConfig子类
        ///子类可以自定义参数以便于覆盖接口相关的配置
        if (serviceConf && serviceConf.__proto__ !== ServiceConfig) {
            throw new Error("Services服务类需要获取一个ServiceOption.class子类作为初始化参数");
        }

        ///默认的话就直接使用内置的ServiceConfig
        if (!serviceConf) serviceConf = ServiceConfig;

        ///属性配置
        resetServiceOptions(serviceConf);

        ///to-do something
        this.domain = serviceConf.DOMAIN;
        this.url = null;

        ///头部可能携带的参数
        this.header = {};

        ///业务参数
        this.params = {};

        ///默认的显示toast
        this.showToast = true;

        ///默认的请求成功不显示toast
        this.successToast = false;

        ///默认的显示loading
        this.showLoading = true;

        ///默认不需要签名加密
        this.needSign = false;

        ///默认的需要权限验证
        this.auth = true;

        ///是否需要序列化
        this.serialize = false;

        ///序列化对应key
        this.serializeKey = serviceOptions.SERIALIZE_PARAM_KEY || 'param';
    }

    /**
     * 核心的请求
     */
    req() {
        ///to-do something with your code ...
    }

    /**
     * 签名封装: 默认的不加入头部签名校验
     */
    sign() {
        let key = serviceOptions.SIGN_KEY || '';

        //判断是否需要签名加密使用
        if (key) this.header[key] = this.needSign ? '1' : '0';

        //携带签名加密串
        if (this.needSign && key) {
            this.header[key] = ""; //签名加密串--后期补充
        }
    }

    /**
     * 拦截请求前的函数
     */
    beforeReq() {
        if (this.auth) {
            let key = serviceOptions.LOCAL_SESSION_KEY || '';
            if (!key) throw "本地存储的session key名字不能为空, LOCAL_SESSION_KEY不能为空了～";

            // 获取skey
            const skey = Storage.get(key);

            ///本地skey为空
            if (!skey) {
                throw new Error("请先登录~");
            }

            // 优先判断是否登录 && 有会话信息头部需要携带token
            let token_key = serviceOptions.TOKEN_KEY || 'TOKEN';
            this.header[token_key] = skey;
        }

        /// 新增时间戳
        let time = new Date().getTime();
        console.log(TAG, 'beforeReq()', '通用参数时间戳time:', time);

        ///默认的初始化
        if (!this.params || Object.keys(this.params).length == 0) this.params = {};
        this.params.timeStamp = time;

        //签名加密
        this.sign();
        return true;
    }

    /**
     * 拦截通用处理后的函数
     * @param {*} res 
     */
    afterReq(res) {
        let code = res.code || "";
        let data = res.data || {};

        if (code == serviceOptions.SUCCESS_CODE) {

            /// 最新token
            let token = data[serviceOptions.RET_TOKEN || 'token'] || '';
            if (token) {
                Storage.set(serviceOptions.LOCAL_SESSION_KEY, token);
            }

            return true;
        }

        //登录失效
        let msg = ((res || {}).msg || '');
        if (code == serviceOptions.ERROR_CODE_01) {
            ///清除本地的会话token
            Storage.clear(serviceOptions.LOCAL_SESSION_KEY);

            //登录失效
            console.error(TAG, msg || "会话失效，请重新登录~")
        }

        return false;
    }
}